package com.yekong.house.web.interceptor;

import com.google.common.base.Joiner;
import com.yekong.house.common.constants.CommonConstants;
import com.yekong.house.common.model.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    /**
     * 在 controller 方法 执行之前拦截执行
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        Map<String,String[]> map = httpServletRequest.getParameterMap();
        map.forEach((k,v)-> {
            if(k.equals("errorMsg")||k.equals("sucessMsg")||k.equals("target")) {
                httpServletRequest.setAttribute(k,Joiner.on(",").join(v));
            }
        });

        String requestUri = httpServletRequest.getRequestURI();
        if(requestUri.startsWith("/static") || requestUri.startsWith("/error")) {
            return  true;
        }
        HttpSession session =  httpServletRequest.getSession(true);
        User user = (User) session.getAttribute(CommonConstants.USER_ATTRIBUTE);
        if(user!=null) {
            UserContext.setUser(user);
        }
        return true;
    }


    /**
     * 在 controller 方法执行完后执行
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }


    /**
     * 在页面渲染完成后执行
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        UserContext.remove();
    }
}
